package com.common;

import com.google.common.base.MoreObjects;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

/**
 * Created by sola on 2018/1/20.
 */
public class QueryCondition implements Pageable {

    private int page;
    private int size;
    private Sort sort;

    public QueryCondition() {
    }

    public QueryCondition(int page, int size) {
        if(page < 0) {
            throw new IllegalArgumentException("Page index must not be less than zero!");
        } else if(size < 1) {
            throw new IllegalArgumentException("Page size must not be less than one!");
        } else {
            this.page = page;
            this.size = size;
        }
    }

    public QueryCondition(int page, int size, Sort sort) {
        if(page < 0) {
            throw new IllegalArgumentException("Page index must not be less than zero!");
        } else if(size < 1) {
            throw new IllegalArgumentException("Page size must not be less than one!");
        } else {
            this.page = page;
            this.size = size;
        }
        this.sort = sort;
    }

    @Override
    public int getPageSize() {
        return this.size;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public void setSort(Sort sort) {
        this.sort = sort;
    }

    @Override
    public int getPageNumber() {
        return this.page;
    }

    @Override
    public int getOffset() {
        return this.page * this.size;
    }

    @Override
    public boolean hasPrevious() {
        return this.page > 0;
    }

    @Override
    public Pageable previousOrFirst() {
        return this.hasPrevious()?this.previous():this.first();
    }

    @Override
    public Pageable first() {
        return new QueryCondition(0, this.getPageSize(), this.getSort());
    }

    @Override
    public Sort getSort() {
        return this.sort;
    }

    @Override
    public Pageable next() {
        return new QueryCondition(this.getPageNumber() + 1, this.getPageSize(), this.getSort());
    }

    public QueryCondition previous() {
        return this.getPageNumber() == 0?this:new QueryCondition(this.getPageNumber() - 1, this.getPageSize(), this.getSort());
    }


    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .add("page", page)
                .add("size", size)
                .add("sort", sort)
                .toString();
    }
}
